package com.yupi.web.aop.inteceptor;

import com.yupi.web.common.ErrorCode;
import com.yupi.web.exception.BusinessException;
import com.yupi.web.model.entity.User;
import com.yupi.web.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

import static com.yupi.web.constant.UserConstant.USER_LOGIN_STATE;

@Component
@Slf4j
public class ApiNumberInteceptor implements HandlerInterceptor {

 @Autowired
  private UserService userService;
    HashMap<String,Integer> map = new HashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        getrequest(request);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String resultRequest = getrequest(request);
        int valueNumber = 1;
        if (map.containsKey(request)){
            Integer number = map.get(request);
            number++;
            map.put(resultRequest,number);
        }else {
            map.put(resultRequest,1);
        }

        System.err.println(map);
    }

    /**
     * 获取接口路径
     * @param request
     * @return
     */
    private static String  getrequest(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        int index = requestURL.indexOf("/");
        String result = requestURL.substring(index + 1);
        log.info("请求方法:.{}", request);
        return result;
    }

}
